package org.zoomdev.zoom.dao.handler;

import org.zoomdev.zoom.dao.SqlConfig;
import org.zoomdev.zoom.dao.adapters.ResultSetMapping;
import org.zoomdev.zoom.dao.configs.Query;
import org.zoomdev.zoom.dao.entity.Entity;
import org.zoomdev.zoom.dao.entity.Field2ColumnMappingConfig;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public final class ListResultSetHandler implements ResultSetHandler {

    @SuppressWarnings("unchecked")
    @Override
    public Object fromResultSet(SqlConfig config, ResultSet rs) throws SQLException {
        ArrayList<Object> result = new ArrayList<>();
        Entity<?> entity = config.getEntity();
        Query query = config.getQuery();
        List<Field2ColumnMappingConfig> list = query.getFields();
        ResultSetMapping<Object> mapping = query.getMapping();
        while (rs.next()) {
            result.add(handleOne(config, entity, mapping, list, rs));
        }
        return result;
    }

    private Object handleOne(SqlConfig config, Entity<?> entity, ResultSetMapping<Object> mapping, List<Field2ColumnMappingConfig> list, ResultSet rs) throws SQLException {
        Object obj = BeanResultSetHandler.fromResultSet(config, entity, list, rs);
        if (mapping != null) {
            mapping.mapping(obj, rs);
        }
        return obj;
    }
}
